import pymysql
import json

from app import db
from flask import Blueprint, render_template, request, url_for, redirect

from app.views.AllBooks import scan_qrcode

bp = Blueprint('BooksOfLent', __name__, url_prefix='/lent')
from app.models import Borrow
from app.models import Book
from app.models import User

# Json序列化
import decimal

import cv2
from pyzbar import pyzbar

class DecimalEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)

@bp.route('/views', methods=['GET', 'POST'])
def lent():
    borrowers = Borrow.query.all()
    book = Book.query.all()
    users = User.query.all()
    context = {
        'inf': users,
        'views': borrowers,
        'books': book
    }
    return render_template('Books Of Lent.html', **context)

@bp.route('/modify', methods=['GET', 'POST'])
def modify():
    bid = request.form['id']
    print(bid)
    borrowers = Borrow.query.filter_by(bid=int(bid)).all()
    print(borrowers)
    borrowLists = [borrow.to_dict() for borrow in borrowers]
    print(borrowLists)
    return json.dumps(borrowLists, cls=DecimalEncoder)

@bp.route('/modifyResult', methods=['PUT'])
def modifyResult():
    bid = request.form['bid']
    username = request.form['username']
    borrowingTime = request.form['borrowingTime']
    remainTime = request.form['remainTime']
    score = request.form['score']

    borrow = Borrow(bid=bid, username=username, borrowingTime=borrowingTime, remainTime=remainTime, score=score)

    print(bid)

    example = Borrow.query.get(int(bid))
    db.session.delete(example)
    db.session.add(borrow)
    db.session.commit()

    borrowers = Borrow.query.all()
    print(borrowers)
    borrowerLists = [borrower.to_dict() for borrower in borrowers]
    print(borrowerLists)
    return json.dumps(borrowerLists, cls=DecimalEncoder)

@bp.route('/delete', methods=['GET', 'POST'])
def delete():
    bid = request.form['name']
    example = Borrow.query.get(bid)
    print(example)
    db.session.delete(example)
    db.session.commit()
    borrowers = Borrow.query.all()
    print(borrowers)
    borrowerLists = [borrower.to_dict() for borrower in borrowers]
    print(borrowerLists)
    return json.dumps(borrowerLists, cls=DecimalEncoder)

@bp.route('/search', methods=['GET', 'POST'])
def search():
    data = request.args.get('search')
    example = Borrow.query.filter_by(bid=int(data))
    print(example)
    context = {
        'views': example
    }
    return render_template('Books Of Lent.html', **context)

@bp.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('addlent.html')
    else:

        bid = request.form['bid']
        username = request.form['username']
        borrowingTime = request.form['borrowingTime']
        remainTime = request.form['remainTime']
        score = request.form['score']

        borrow = Borrow(bid=bid, username=username, borrowingTime=borrowingTime, remainTime=remainTime, score=score)

        db.session.add(borrow)
        db.session.commit()

    return redirect(url_for('BooksOfLent.lent'))

@bp.route('/returnBorrow', methods=['GET', 'POST'])
def returnBorrow():
    borrowers = Borrow.query.all()
    borrowerLists = [borrower.to_dict() for borrower in borrowers]
    return json.dumps(borrowerLists, cls=DecimalEncoder)

@bp.route('/returnByQRcode', methods=['GET', 'POST'])
def returnByQRcode():
    bid = request.form['name']
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        cv2.imshow('scan qrcode', frame)

        # 解析二维码
        text = None
        try:
            text = scan_qrcode(frame)
        except Exception as e:
            pass
        if text:
            print(text)
            break

        key = cv2.waitKey(10)
        if key == ord('q'):
            break
    cv2.destroyAllWindows()

    example = Borrow.query.get(bid)
    print(example)
    db.session.delete(example)
    db.session.commit()
    borrowers = Borrow.query.all()
    print(borrowers)
    borrowerLists = [borrower.to_dict() for borrower in borrowers]
    print(borrowerLists)

    return json.dumps(borrowerLists, cls=DecimalEncoder)
